package com.example.kiratest.realize.Service.Impl;

import com.example.kiratest.realize.Service.PythonService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

//在Linux中调用打包好的文件
@Service("pythonServiceImpl")
public class PythonServiceImpl implements PythonService {

    @Override
    public String execute() throws URISyntaxException, IOException {
        // 1. 准备参数
        String packageName = "com.mobile.legends";
        String lang = "en";
        String country = "us";

        // 2. 调用Python脚本并获取结果
        String version = getAppVersionFromPython(packageName, lang, country);

        // 3. 处理结果
        if (version != null) {
            System.out.println("成功获取版本号: " + version);
        } else {
            System.err.println("获取版本号失败");
        }
        return version != null ? version : null;
    }

    private static String getAppVersionFromPython(String packageName, String lang, String country) throws URISyntaxException, IOException {

        // 如果脚本在resources/other目录下
        InputStream inputStream = PythonServiceImpl.class.getResourceAsStream("/other/getVersionChange");
        Path tempFile = Files.createTempFile("getVersionChange", "");
        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
        tempFile.toFile().setExecutable(true);
        String executablePath = tempFile.toAbsolutePath().toString();


        String[] command = {
                executablePath,
                packageName,
                lang,
                country
        };

        // 打印完整命令用于调试
        System.out.println("[DEBUG] 执行命令: " + String.join(" ", command));

        // 2. 执行命令
        try {
            Process proc = Runtime.getRuntime().exec(command);

            // 读取输出和错误流
            StringBuilder output = readStream(proc.getInputStream());
            StringBuilder error = readStream(proc.getErrorStream());

            int exitCode = proc.waitFor();
            if (exitCode == 0) {
                return output.toString();
            } else {
                System.err.println("执行失败！错误信息:\n" + error);
                return null;
            }
        } catch (Exception e) {
            System.err.println("运行时异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    // 辅助方法：读取流数据
    private static StringBuilder readStream(InputStream input) throws IOException {
        StringBuilder result = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
        }
        return result;
    }
}
